package org.jeecg.modules.flower.controller;

import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.chvegetable.entity.FlowerTagBook;
import org.jeecg.modules.chvegetable.service.IFlowerTagBookService;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.service.IFlowerCustomService;
import org.jeecg.modules.flower.service.IFlowerOutorderService;
import org.jeecg.modules.flower.service.IFlowerTagPrintService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.flower.vo.FlowerOutorderPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 标签打印表-新版
 * @Author: jeecg-boot
 * @Date: 2022-10-13
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "标签打印表-新版")
@RestController
@RequestMapping("/flower/flowerTagPrint")
public class FlowerTagPrintController extends JeecgController<FlowerTagPrint, IFlowerTagPrintService> {
    @Autowired
    private IFlowerTagPrintService flowerTagPrintService;

    @Autowired
    private IFlowerOutorderService flowerOutorderService;
    @Autowired
    private IFlowerTagBookService flowerTagBookService;
    @Autowired
    private IFlowerCustomService flowerCustomService;

    /**
     * 分页列表查询
     *
     * @param flowerTagPrint
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "标签打印表-新版-分页列表查询")
    @ApiOperation(value = "标签打印表-新版-分页列表查询", notes = "标签打印表-新版-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "flower/FlowerTagPrintList")
    public Result<?> queryPageList(FlowerTagPrint flowerTagPrint,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<FlowerTagPrint> queryWrapper = QueryGenerator.initQueryWrapper(flowerTagPrint, req.getParameterMap());
        Page<FlowerTagPrint> page = new Page<FlowerTagPrint>(pageNo, pageSize);
//        QueryGenerator.installAuthMplus(queryWrapper, FlowerTagPrint.class);
        IPage<FlowerTagPrint> pageList = flowerTagPrintService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param flowerTagPrint
     * @return
     */
    @AutoLog(value = "标签打印表-新版-添加")
    @ApiOperation(value = "标签打印表-新版-添加", notes = "标签打印表-新版-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody FlowerTagPrint flowerTagPrint) {
        if(flowerTagPrint.getState()==null){
            flowerTagPrint.setState(0);
        }
        flowerTagPrintService.save(flowerTagPrint);
        return Result.OK(flowerTagPrint);
    }

    /**
     * 编辑
     *
     * @param flowerTagPrint
     * @return
     */
    @AutoLog(value = "标签打印表-新版-编辑")
    @ApiOperation(value = "标签打印表-新版-编辑", notes = "标签打印表-新版-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> edit(@RequestBody FlowerTagPrint flowerTagPrint) {
        flowerTagPrintService.updateById(flowerTagPrint);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "标签打印表-新版-通过id删除")
    @ApiOperation(value = "标签打印表-新版-通过id删除", notes = "标签打印表-新版-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        FlowerTagPrint byId = flowerTagPrintService.getById(id);
        if(byId.getState().compareTo(1)==0){
            throw new RuntimeException("已入库数据不可删除！");
        }
        flowerTagPrintService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "标签打印表-新版-批量删除")
    @ApiOperation(value = "标签打印表-新版-批量删除", notes = "标签打印表-新版-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<FlowerTagPrint> list = flowerTagPrintService.listByIds(Arrays.asList(ids.split(",")));
        for(FlowerTagPrint  byId : list) {
            if (byId.getState().compareTo(1) == 0) {
                throw new RuntimeException("存在已入库数据不可删除！");
            }
        }
        this.flowerTagPrintService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "标签打印表-新版-通过id查询")
    @ApiOperation(value = "标签打印表-新版-通过id查询", notes = "标签打印表-新版-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        FlowerTagPrint flowerTagPrint = flowerTagPrintService.getById(id);
        return Result.OK(flowerTagPrint);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param flowerTagPrint
     */
    @RequestMapping(value = "/exportXls")
    @PermissionData(pageComponent = "flower/FlowerTagPrintList")
    public ModelAndView exportXls(HttpServletRequest request, FlowerTagPrint flowerTagPrint) {
        return super.exportXls(request, flowerTagPrint, FlowerTagPrint.class, "标签打印表-新版");
    }



    /**
     * 标签打印表-新版-扫码入库
     *
     * @return org.jeecg.common.api.vo.Result<?>
     * @descriptionauthor
     * @author gf
     * 2022-10-13 10:38
     * [id, storehouse, req]
     */
    @AutoLog(value = "标签打印表-新版-扫码入库-电脑扫码枪")
    @ApiOperation(value = "标签打印表-新版-扫码入库电脑扫码枪", notes = "标签打印表-新版-扫码入库电脑扫码枪")
    @GetMapping(value = "/scanIn")
    public Result<?> scanIn(@RequestParam(name = "ids") String ids,
                            @RequestParam(name = "storehouse") String storehouse,
                            @RequestParam(name = "productionId") String productionId,
                            HttpServletRequest req) {

        Integer integer = flowerTagPrintService.ScanInTagInfo( Arrays.asList(ids.split(",")), storehouse,productionId);
        return Result.OK("入库成功！"+ integer );
    }
    /**
     * 标签打印表-新版-扫码入库
     *
     * @return org.jeecg.common.api.vo.Result<?>
     * @descriptionauthor
     * @author gf
     * 2022-10-13 10:38
     * [id, storehouse, req]
     */
    @AutoLog(value = "标签打印表-新版-扫码入库-PDA专用")
    @ApiOperation(value = "标签打印表-新版-扫码入库-PDA专用", notes = "标签打印表-新版-扫码入库-PDA专用")
    @GetMapping(value = "/scanInForPDA")
    public Result<?> scanInForPDA(@RequestParam(name = "ids") String ids,
                            @RequestParam(name = "storehouse") String storehouse,
                            @RequestParam(name = "productionId") String productionId,
                            HttpServletRequest req) {

        Integer integer = flowerTagPrintService.ScanInTagInfo( Arrays.asList(ids.split(",")), storehouse,productionId);
        return Result.OK("入库成功！"+ integer );
    }



    /**
     * PDA扫码出库-新版-扫码出库--将扫码的ids存起来
     * @descriptionauthor
     * @author gf
     * 2022-11-4 15:56
     * [ids, storehouse, req]
     * @return org.jeecg.common.api.vo.Result<?>
     */
    @AutoLog(value = "PDA扫码出库-新版-扫码出库")
    @ApiOperation(value = "PDA扫码出库-新版-扫码出库", notes = "PDA扫码出库-新版-扫码出库---将扫码的ids存起来")
    @GetMapping(value = "/scanOutForPDA")
    public synchronized Result<?> scanOutForPDA(@RequestParam(name = "orderNo") String orderNo,
                                  @RequestParam(name = "ids") String ids,
                                  HttpServletRequest req) {
        String rest = flowerTagPrintService.ScanOutPDAByIds( ids , orderNo);
        return Result.OK(rest);
    }


    /**
     * PDA扫码出库-新版-扫码出库--确认出库
     * @descriptionauthor
     * @author gf
     * 2022-11-4 15:56
     * [ids, storehouse, req]
     * @return org.jeecg.common.api.vo.Result<?>
     */
    @AutoLog(value = "PDA扫码出库-新版-确认扫码出库")
    @ApiOperation(value = "PDA扫码出库-新版-确认扫码出库", notes = "PDA扫码出库-新版-确认扫码出库---根据订单编号将标签表和入库表的标签进行出库")
    @GetMapping(value = "/scanOutForPDASure")
    public synchronized Result<?> scanOutForPDASure(@RequestParam(name = "orderNo") String orderNo,
                                  HttpServletRequest req) throws IOException {
        String rest = flowerTagPrintService.ScanOutPDASure(  orderNo );
        return Result.OK(rest);
    }



    /**
     * PDA扫码出库-新版-删除关联的扫码标签关联单
     * @descriptionauthor
     * @author gf
     * 2022-11-4 15:56
     * [ids, storehouse, req]
     * @return org.jeecg.common.api.vo.Result<?>
     */
    @AutoLog(value = "PDA扫码出库-新版-删除关联的扫码标签关联单")
    @ApiOperation(value = "PDA扫码出库-新版-删除关联的扫码标签关联单", notes = "PDA扫码出库-新版-删除该出库单关联的扫码标签关联单")
    @DeleteMapping (value = "/ScanOutPDADeleteByOrderno/{orderNo}")
    public Result<?> ScanOutPDADeleteByOrderno(@PathVariable(name = "orderNo") String orderNo,
                                       HttpServletRequest req) {
        String rest = flowerTagPrintService.ScanOutPDADeleteByOrderno(  orderNo );
        return Result.OK(rest);
    }

    /**
     *
     *s散货出库
     *s散货出库
     *s散货出库
     *s散货出库
     * @descriptionauthor
     * @author gf
     * 2023-3-27 18:04
     * [orderNo, req]
     * @return org.jeecg.common.api.vo.Result<?>
     */
    @AutoLog(value = "PDA-新版-s散货出库")
    @ApiOperation(value = "PDA-新版-s散货出库", notes = "PDA -新版-s散货出库")
    @PostMapping (value = "/sanHuoChuKu")
    public Result<?> sanHuoChuKu(@RequestBody FlowerOutorderPage flowerOutorder,
                                 HttpServletRequest req) throws IOException {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        String user = flowerOutorder.getUser();
        String userid = flowerOutorder.getUserid();
        FlowerCustom custom = flowerCustomService.getById(userid);
        flowerOutorder.setPhone (custom.getPhone());
        flowerOutorder.setAddress(custom.getAddress());
        flowerOutorder.setTouser(user);
        flowerOutorder.setTophone(custom.getPhone());
        FlowerOutorder flowerOutorder1 = new FlowerOutorder();
        BeanUtils.copyProperties(flowerOutorder,flowerOutorder1);

        flowerOutorder1.setOrderNo(null);
        flowerOutorder1.setStockOutUser( sysUser.getRealname());
        flowerOutorder1.setStockInTime( new Date());
        flowerOutorder1.setType( "0");
        flowerOutorder1.setBusinessPerson( sysUser.getRealname());
        flowerOutorder1.setPhone(  "无");
        flowerOutorder1.setTouser(  user);
        flowerOutorder1.setState(  0);
        flowerOutorder1.setIsinvoice("否");

        List<FlowerOutorderinfo> flowerOutorderinfoList = flowerOutorder.getFlowerOutorderinfoList();

        for(FlowerOutorderinfo flowerOutorderinfo : flowerOutorderinfoList){
            String bookid = flowerOutorderinfo.getId();
            LambdaQueryWrapper<FlowerTagBook> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(FlowerTagBook::getStorehouse,flowerOutorderinfo.getStorehouse());
            queryWrapper.eq(FlowerTagBook::getPackingSpecifications,flowerOutorderinfo.getPackingSpecifications());
            queryWrapper.eq(FlowerTagBook::getFlowerPoleLength,flowerOutorderinfo.getFlowerPoleLength());
            queryWrapper.eq(FlowerTagBook::getClasses,flowerOutorderinfo.getClasses());
            queryWrapper.eq(FlowerTagBook::getVariety,flowerOutorderinfo.getVariety());

            List<FlowerTagBook> list = flowerTagBookService.list(queryWrapper);
            if(list.size()==0){
                throw new RuntimeException("未找到该商品库存");
            }
            FlowerTagBook bybook = list.get(0);

            flowerOutorderinfo.setId(UuidUtils.getUUID());

            flowerOutorderinfo.setVarietyCode(bybook.getVarietyCode());
            flowerOutorderinfo.setSourceBase(bybook.getSourceBase());
            flowerOutorderinfo.setSourceGreenhouse(bybook.getSourceGreenhouse());
            flowerOutorderinfo.setStorehouse(bybook.getStorehouse());
            flowerOutorderinfo.setCost(bybook.getCost());
            flowerOutorderinfo.setProductionId(bybook.getProductionId());
            flowerOutorderinfo.setFlowerPoleLength(bybook.getFlowerPoleLength());

            flowerOutorderinfo.setPrice( flowerOutorderinfo.getNumber() );
            flowerOutorderinfo.setTotalprice( flowerOutorderinfo.getNumber().multiply(flowerOutorderinfo.getNumber()) );
        }
        flowerOutorderService.saveMain(flowerOutorder1,flowerOutorderinfoList);

        return Result.OK( );
    }




    /**
     * -分组查询名称，用于下拉
     *
     * @param
     * @return
     */
    @AutoLog(value = "蔬菜品种表-分组查询名称，用于下拉")
    @ApiOperation(value="蔬菜品种表--分组查询名称，用于下拉", notes="蔬菜品种表--分组查询名称，用于下拉")
    @GetMapping(value = "/queryNames")
    public Result<?> queryNames( @RequestParam("storehouse") String storehouse) {
        QueryWrapper<FlowerTagBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("storehouse",storehouse);
        queryWrapper.groupBy("variety");
        queryWrapper.orderByAsc("variety");
        List<FlowerTagBook> flowerVarietyList = flowerTagBookService.list(queryWrapper);
        return Result.ok(flowerVarietyList);
    }
    /**
     *
     *-根据名称查询规格，用于下拉
     * @descriptionauthor
     * @author gf
     * 2023-4-3 9:59
     * [storehouse, variety]
     * @return org.jeecg.common.api.vo.Result<?>
     */
    @AutoLog(value = "蔬菜品种表-根据名称查询规格")
    @ApiOperation(value="蔬菜品种表--根据名称查询规格，用于下拉", notes="蔬菜品种表--根据名称查询规格，用于下拉")
    @GetMapping(value = "/queryPacksByName")
    public Result<?> queryPacksByName( @RequestParam("storehouse") String storehouse, @RequestParam("variety") String variety ) {
        QueryWrapper<FlowerTagBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("packing_specifications");
        queryWrapper.eq("storehouse",storehouse);
        queryWrapper.eq("variety",variety);
        queryWrapper.groupBy("packing_specifications");
        queryWrapper.orderByAsc("packing_specifications");
        List<FlowerTagBook> flowerVarietyList = flowerTagBookService.list(queryWrapper);
        return Result.ok(flowerVarietyList);
    }



    @AutoLog(value = "蔬菜品种表-分组查询等级-根据名称、规格")
    @ApiOperation(value="蔬菜品种表--分组查询等级-根据名称、规格，用于下拉", notes="蔬菜品种表--分组查询等级-根据名称、规格，用于下拉")
    @GetMapping(value = "/queryClassesByName")
    public Result<?> queryClassesByName( @RequestParam ("storehouse") String storehouse, @RequestParam("variety") String variety , @RequestParam("packing") String packing) {
        QueryWrapper<FlowerTagBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("storehouse",storehouse);
        queryWrapper.eq("variety",variety);
        queryWrapper.eq("packing_specifications",packing);
        queryWrapper.select("classes");
        queryWrapper.groupBy("classes");
        queryWrapper.orderByAsc("classes");
        List<FlowerTagBook> flowerVarietyList = flowerTagBookService.list(queryWrapper);
        return Result.ok(flowerVarietyList);
    }

    /**
     *
     *分组查询长度，用于下拉
     * @descriptionauthor
     * @author gf
     * 2023-4-3 10:19
     * [storehouse, variety, packing, classes]
     * @return org.jeecg.common.api.vo.Result<?>
     */
    @AutoLog(value = "蔬菜品种表-分组查询单位")
    @ApiOperation(value="蔬菜品种表--分组查询单位，用于下拉", notes="蔬菜品种表--分组查询单位，用于下拉")
    @GetMapping(value = "/queryLengthByName")
    public Result<?> queryLengthByName(@RequestParam ("storehouse") String storehouse, @RequestParam("variety") String variety ,  @RequestParam("packing") String packing, @RequestParam("classes") String classes) {
        QueryWrapper<FlowerTagBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("storehouse",storehouse);
        queryWrapper.eq("variety",variety);
        queryWrapper.eq("packing_specifications",packing);
        queryWrapper.eq("classes",classes);
        queryWrapper.select("flower_pole_length");
        queryWrapper.groupBy("flower_pole_length");
        queryWrapper.orderByAsc("flower_pole_length");
        List<FlowerTagBook> flowerVarietyList = flowerTagBookService.list(queryWrapper);
        return Result.ok(flowerVarietyList);
    }
}
